<?php
/*
 * 生成素材缩略图
 * @author ljx
 * 方法说明：绝对路径(p1) + 相对路径(p2)  + 文件级目录(p3) + 文件名称(p4)
 * example:  \\192.168.1.5\share\yofuseditor_debug\resource + design + 
 * photobook\classic_with_window_12x8\solid_color_series\obsessed_with_coffee\background + a.jpg
 
 使用范例：
 * 生成前背景图：http://192.168.1.5/ecshop/resource.php?styleid=106
 * 产品级缩略图: http://192.168.1.5/ecshop/resource.php?productid=13
 * 共享级缩略图: http://192.168.1.5/ecshop/resource.php?act=sharestyle
 * 生成修饰图：http://192.168.1.5/ecshop/resource.php?act=ass
 */

//exit();
ob_start(); //打开输出缓冲区 
ob_end_flush(); 
ob_implicit_flush(1); //立即输出

define ( 'IN_ECS', true );

if(count($argv)<=0)
{
include (dirname ( __FILE__ ) . '/includes/init.php');
}
else
{
	define('ROOT_PATH','/var/www/www.yofus.com/');
	$_SERVER['SERVER_NAME'] = "www.yofus.com";
	include (dirname ( __FILE__ ) . '/includes/init.php');
}
include_once ROOT_PATH . 'includes/cls_image.php';
include_once ROOT_PATH . 'includes/lib_time.php';
include_once ROOT_PATH . 'includes/yofus/common/img_size.php';//缩略图规格说明
$style = urldecode($_GET["style"]);
if(empty($style))
{
	if($argc >=2)
	{
	$style = urldecode($argv[1]);
	}
}
if(empty($style))
{
    die("need param style");
}
$style = str_replace("\\\\",DIRECTORY_SEPARATOR,$style);

$style = str_replace("\\",DIRECTORY_SEPARATOR,$style);

//生成缩略图目录
//$thumb_dir = 'E:' . DIRECTORY_SEPARATOR;
set_time_limit(0);

$arr_file = array ('.jpg', '.gif', '.png' );
//前背景图
//$arr_bg_img_size = array('60','120','400','800');
//修饰图：120/200/500/800
//$arr_decorate_img_size = array('15','30','60','120','200','400','800');
global $arr_bg_img_size,$arr_decorate_img_size,$arr_size_to_str;
$start_time = gmtime();
echo "开始时间：" . date("H:i:s",$start_time) . "<br/>";
ob_flush();
/*
 * 测试本地
 * $p1 = "D:" . DIRECTORY_SEPARATOR;
$p2 = '';//design manufacture
$p3 = 'calendar' . DIRECTORY_SEPARATOR . 'width_oblong_11x6';
$resource_path = $p1 . $p2 . $p3;*/
/*
**example:\design\photobook\classic_with_window_12x8\solid_color_series\obsessed_with_coffee\
** 目录级
** 'design' . DIRECTORY_SEPARATOR . $result['class'] . DIRECTORY_SEPARATOR . $result['product'] . DIRECTORY_SEPARATOR . $result['theme'] . DIRECTORY_SEPARATOR . $result['style']
**目录包含：background  foreground
//共享级
**example:\design\photobook\classic_with_window_12x8\shareproductres_5\
**$base_layout_path = 'design' . DIRECTORY_SEPARATOR . $result['class'] . DIRECTORY_SEPARATOR . $result['product'] . DIRECTORY_SEPARATOR . 'shareproductres_'.$result['id']
**目录包含：background   decorate   foreground
**全局级
**example:design\globalres\decorate
**'design' . DIRECTORY_SEPARATOR . 'globalres'
**目录包含：decorate
1：如果有传递style_id ,按指定的产品生成缩略图
2:没有style_id ,系统循环数据表
$resource_path = '';//素材目录绝对路径
*/
//$thumb_dir = '/export/resource/';
$thumb_dir = $_EXT_CFG['resource_root'];

//$p1 = '/export/resource/';
$p1 = $_EXT_CFG['resource_root'];
$p2 = 'design/';


if($argc >=2)
{
        $thumb_dir = '/export/resource/';
	$p1 = '/export/resource/';
}
echo "\r\nbasedir:" . $thumb_dir . "\r\n";
ob_flush();
$obj_sqlite = getSqlite();

$style_id = isset($_REQUEST['styleid']) ? intval($_REQUEST['styleid']) : 0;
$product_id = isset($_REQUEST['productid']) ? intval($_REQUEST['productid']) : 0;
$sharestyle = isset($_REQUEST['act']) && $_REQUEST['act'] == 'sharestyle';
$decorate = isset($_REQUEST['act']) && $_REQUEST['act'] == 'ass';
$const_img_siez = array();
$result = array();


$resource_path = $style;
$arr_img_dir = getdiesbyStylePath($resource_path);
echo "\r\nfound directory: " . count($arr_img_dir) . "\r\n";
ob_flush();
foreach($arr_img_dir as $item)
{
	if(substr($path,-8) == "decorate")
	{
		$const_img_siez = $arr_decorate_img_size;
	}
	else
	{
		$const_img_siez = $arr_bg_img_size;	
	}
              $p3 = $item;
              $resource_path = $p1 . $p2 . $p3;
              getfiles($resource_path);
}
function getdiesbyStylePath($style_template_path)
{
	$arr_img_dir[] =  $style_template_path . 'frame';
	 $arr_img_dir[] =  $style_template_path . 'decorate';
         $arr_img_dir[] =  $style_template_path . 'background';
         $arr_img_dir[] = $style_template_path . 'foreground';
	$arr_img_dir[] =  $style_template_path . 'layout_bg'; 
	$arr_img_dir[] =  $style_template_path . 'layout_fg';
	return $arr_img_dir;
}


//getfiles($resource_path);

$end_time = gmtime();
echo "结束时间：" . date("H:i:s",$end_time) . "<br/>";
ob_flush();
$result_time = $end_time - $start_time;
echo "运行时间：" . $result_time . 's';
ob_flush();

exit();

function getSqlite()
{
	include_once(constant("ROOT_PATH") . "amfphp/lib/sqliteDB.php");
	$sqlite_profile = constant("ROOT_PATH") . "resource/profile_yofus.dat";
	if(!file_exists($sqlite_profile))
	$sqlite_profile =  "\\\\192.168.1.5\\share\\ecshop\\resource\\profile_yofus.dat";
	
	//连接sqlite
	$obj_profile = @new sqliteDB ( "sqlite:" . $sqlite_profile );
	return $obj_profile;
}
function get_sharestyles_sql()
{
    $sql  = "select * from product_style  where type=1";
    return $sql;
}

function get_sql($styleID)
{
	$sql  = "SELECT st.alias as style,su.alias as theme,p.alias as product,c.[alias] as class,p.id";
    $sql .= " FROM product_style as st,product_subject as su,product as p,product_class as c";
    $sql .= " WHERE st.id = '$styleID' and su.id = st.subject_id and p.id = su.product_id and c.id =  p.class_id";
    return $sql;
}

function getStyleID()
{
	$sql = "SELECT id FROM product_style WHERE type = '0'";
	return $sql;
}

function getProductTOStyleID($prodouctid)
{
	$sql = "SELECT st.id as id FROM product as p,product_subject as su,product_style as st";
	$sql .= " WHERE p.id = '" . $prodouctid . "' AND su.product_id = p.id AND su.id = st.subject_id AND st.type = '0'";
	return $sql;
}
function get_templatedir_bystyleId($style_id)
	{
	    $style_id = intval( $style_id );
		if(empty( $style_id )) return false; 
		
		include_once( ROOT_PATH . "amfphp/lib/sqliteDB.php" );
		$sqlite_profile = ROOT_PATH . "resource/profile_yofus.dat";
		$obj_profile    = @new sqliteDB ( "sqlite:" . $sqlite_profile );
		
		$str_sql_type   = "SELECT type FROM product_style WHERE id = $style_id LIMIT 1"; 
		$res_type       = $obj_profile->query( $str_sql_type );
	 	
		if( empty( $res_type ) ) return false;
		$data_type = $res_type[0];
		
		if( $data_type['type'] == 1 )
		{
		    $str_sql_share = "SELECT share_level, parent_id FROM commonres WHERE style_id = $style_id LIMIT 1"; 
			$share_res     = $obj_profile->query( $str_sql_share );
			if( empty( $share_res ) ) return false;
			$share_data  = $share_res[0];
			
			$share_level = $share_data["share_level"];
			$subject_id  = $share_data["parent_id"];
			
			if( $share_level == "global" )
			{
				$middle_path = "globalres/";
			}
			else
			{
				$str_sql_search  = "SELECT C.alias calias, P.alias palias, P.id pid, S.alias salias FROM product_class C, "; 
				$str_sql_search .= "product P, product_subject S WHERE C.id = P.class_id AND P.id = S.product_id AND ";
				$str_sql_search .= "S.id = $subject_id LIMIT 1";
				$path_data       = $obj_profile->query( $str_sql_search );
				
				if( empty( $path_data ) ) return false;
				$arr_path   = $path_data[0];
				$common_path = $arr_path["calias"] . "/" . $arr_path["palias"];
				
				if( $share_level == "product" )
				{
					$middle_path = $common_path . "/shareproductres_" . $arr_path["pid"];
				}
				else if( $share_level == "subject" )
				{
					$middle_path = $common_path . "/" . $arr_path["salias"] . "/sharesubjectres_" . $subject_id;
				}
			}
		}
		else
		{
		    $str_sql_st  = "SELECT C.alias calias, P.alias palias, S.alias salias, PS.alias psalias, PS.type type "; 
			$str_sql_st .= "FROM product_class C, product P, product_subject S, product_style PS WHERE C.id = P.class_id AND ";
			$str_sql_st .= "P.id = S.product_id AND S.id = PS.subject_id AND PS.id = $style_id LIMIT 1";
			$res         = $obj_profile->query( $str_sql_st );
			
			if( empty( $res ) ) return false;
			$path_value  = $res[0];
			$middle_path = $path_value["calias"] . "/" . $path_value["palias"] . "/" . $path_value["salias"] . "/" . $path_value["psalias"];
		}
		
		$style_template_path = $middle_path . "/";

		$arr_img_dir[] =  $style_template_path . 'background';
                $arr_img_dir[] = $style_template_path . 'foreground';
                return $arr_img_dir;
	}
function get_dir_img($result)
{
	global $decorate,$style_id,$product_id;
	$arr_img_dir = array();
	//修试图单独处理
	if (!empty($decorate))
	{
		$arr_img_dir[] = 'globalres' . DIRECTORY_SEPARATOR . 'decorate';
	}
	else
	{
		foreach ($result as $val)
		{
			/**
			 * 2011-7-28
			 * edit:ljx
			 * 更改为到产品级目录，不用考虑目录结构不规范问题。
			 * $arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'];
			 */
			
			$arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'] . DIRECTORY_SEPARATOR . $val['theme'] . DIRECTORY_SEPARATOR . $val['style'] . DIRECTORY_SEPARATOR . 'background';
			$arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'] . DIRECTORY_SEPARATOR . $val['theme'] . DIRECTORY_SEPARATOR . $val['style'] . DIRECTORY_SEPARATOR . 'foreground';

			$arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'] . DIRECTORY_SEPARATOR . 'shareproductres_'.$val['id'] . DIRECTORY_SEPARATOR . 'background';
			$arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'] . DIRECTORY_SEPARATOR . 'shareproductres_'.$val['id'] . DIRECTORY_SEPARATOR . 'foreground';
			$arr_img_dir[] = $val['class'] . DIRECTORY_SEPARATOR . $val['product'] . DIRECTORY_SEPARATOR . 'shareproductres_'.$val['id'] . DIRECTORY_SEPARATOR . 'decorate';
		}
	}
		
	return $arr_img_dir;
}

function create_resource_Thumb($path_file, $file_name, $path) {
	global $const_img_siez,$arr_size_to_str;
	//获取预览图的宽度和高度
	if (!file_exists($path_file))
	{
		echo "<br/>生成缩略图的原始图片不存在:" . $path_file;
		ob_flush();
		return false;
	}
	$str_replace = '';
	$arr_img_data = @getimagesize ( $path_file );
	$int_img_width = $arr_img_data [0];
	$int_img_height = $arr_img_data [1];
	$max = ($int_img_height > $int_img_width) ? $int_img_height : $int_img_width;
	//提前判断图片尺寸
	foreach ($const_img_siez as $key =>$item)
	{
		if ($item > $max)
		{
			$num = $key;
			break;
		}
		$num = $key;
	}
//	trace ( "原始图片大小：宽：" . $int_img_width . "高：" . $int_img_height . "名称：" . $file_name );
	//不设置内存限制
	ini_set ( "memory_limit", "128M" );
	//生成中等缩略图
	$arr_thumb = array ();
	//真是图的名字
	$arr_thumb ["file_name"] = $path_file;
	//缩略图的名字
	$arr_filename = explode ( ".", $file_name );
	$arr_thumb ["img_type"] = $arr_filename[1];
	$str = '';
	for ($i=0;$i<=$num;$i++){
//	foreach ( $arr_bg_img_size as $key => $item ) {
		$size = $const_img_siez[$i];
		
		if (array_search($size,$arr_size_to_str))
			{
				$str_replace = array_search($size,$arr_size_to_str);
			}
			else {
				$str_replace = $size;
			}
		$arr_thumb ["thumb_name"] = $arr_filename [0] . "_" . $str_replace . cls_image::get_filetype ( $file_name ); //$str_thumb_name;
		$arr_thumb ["times"] = 1;
		$arr_thumb ["path"] = $path;
		$arr_thumb ["thumb_width"] = $size;
		$arr_thumb ["thumb_height"] = $size;
		$arr_thumb ["file_width"] = $int_img_width;
		$arr_thumb ["file_height"] = $int_img_height;
//		$flag = check_img($file_name,$path_file);
/*		if ($flag)
		{*/
			if (!void_make_thumb($arr_thumb))
			{
				echo "生成缩略图失败<br/>";
				ob_flush();
				print_r($arr_thumb);
				return false;
			}			
			
			if ($i == $num)
			{
				$str .= '"' . $str_replace . '"';
			}
			else {
				$str .= '"' . $str_replace . '",';
			}			
//		}
	}
//	echo $str . "<br/>";
	return $str;
}
/*
 * 查询路径：$root_path
 * 文件路径：$path_file
 * 文件名称：$img_name
 */
function check_img($img_name,$path_file)
{
	if (!empty($img_name))
	{
		//eg:a_300.jpg
		if (preg_match('/^(.)+[_][\d]+[.](gif|jpg|png|jpeg)$/',$img_name))
		{
			return false;
		}
		else {
			if (file_exists($path_file))
			{
				return true;
			}
			return false;
		}
	}
	return false;
/*	$str_dbfile = $root_path . "resourc.db3";
	if (!file_exists($str_dbfile))
	{
		$str_db_img = ROOT_PATH . "amfphp/lib/resourc.db3";
		if (!copy($str_db_img,$str_dbfile))
		{
			echo "复制数据文件失败";
			ob_flush();
			exit();
		}
	}
	$obj_sqlite = obj_connect_sqlite ( $str_dbfile );
	$info_img = $obj_sqlite->query("SELECT * FROM infoimg WHERE file_name = '" . $img_name . "'");
	if (count($info_img) == 0)
	{
		return true;
	}
	$file_md5 = md5_file($url_path . $img_name);
	if ($file_md5 == $info_img[0]['file_md5'])
	{
		return true;
	}
	return false;*/
}

function getfiles($path) 
{
	echo "\r\b getfiles for: " . $path . "\r\n";
	ob_flush();
	global $arr_file,$thumb_dir,$p1,$p2,$p3;
	if(strpos($path,'.svn'))
	{
		echo "<br/>检查。svn，直接跳过" . $path;
		ob_flush();
		return ;
	}
	if (! is_dir ( $path )) 
	{
		echo "<br/>指定的目录不存在,已经跳过：" . $path;
		ob_flush();

		return ;
	}
	$fp = opendir ( $path );
	//消除前面绝对路径,获取相对路径
	$new_path = trim(str_replace($p1.$p2,"",$path));
//	echo "getfiles()" . $new_path;
	$flag_create_dir = creat_thume_dir($thumb_dir,'thumb' . DIRECTORY_SEPARATOR . $new_path);
	if (!$flag_create_dir)
	{
		echo "创建目录失败,直接退出";
		ob_flush();
		exit();
	}
	
	$str = "";
	while ( false !== ($file = readdir ( $fp )) ) {
		if ($file != '.' && $file != '..') 
		{
			$path2 = $path . '/' . $file;
                        ob_flush();	
			if (is_dir ( $path2 )) 
			{
				getfiles ( $path2 );
			} 
			else 
			{
				if (in_array ( cls_image::get_filetype ( $file ), $arr_file )) 
				{
					echo "\r\nprocess file:" . $path2 . "  ";
					$str_thumb = create_resource_Thumb($path2,$file,$flag_create_dir);
					if ($str_thumb)
					{
						echo "ok\r\n";
						$str .= '"' .$file . '"' . ':' . '[' . $str_thumb . '],';
						write_thumb_metaflag($flag_create_dir,$str);
					}
					else
					{
						echo "fail\r\n";
					}
				}
			
			}
		}
	}
}

function write_thumb_metaflag($path,$str)
{
	$filename = $path . 'thumb.txt';
	$str = '{' .trim($str,',') . '}';
//	echo $str . "<br/>";
	$fp = fopen($filename,'w+');
	if(!$fp) {
		die("open file faile:" . $filename);
	}
	fwrite($fp,$str);
	flush($fp);
	fclose($fp);
}

function creat_thume_dir($thumb_dir,$dir)
{
	$arr_dir = explode(DIRECTORY_SEPARATOR,$dir);
	foreach ($arr_dir as $val)
	{
		$thumb_dir .= $val . DIRECTORY_SEPARATOR;
//		echo "<br/>" .$thumb_dir . "<br/>";
		if (!is_dir($thumb_dir))
		{
			if (mkdir($thumb_dir))
			{
				continue;
			}
			else 
			{
				echo "创建文件夹失败：" . $thumb_dir;
				ob_flush();
				return false;
			}
		}
	}
	return $thumb_dir;
}
function void_make_thumb($pam_params)
{
	//原图文件地址
	$str_file_name  = $pam_params["file_name"];
	//压缩后文件地址
	$str_thumb_name = $pam_params["thumb_name"];
	//压缩次数
	$int_times = $pam_params["times"];
	//项目路径
	$str_path  = $pam_params["path"];

	$int_conf_width  = $pam_params["thumb_width"];
	$int_conf_height = $pam_params["thumb_height"];
	$str_img_type = $pam_params["img_type"];


	//获取压缩后的高度和宽度（比例）
	if($pam_params["file_height"] > $pam_params["file_width"]){
		$arr_thumbs = getImageRate($pam_params["file_height"],$pam_params["file_width"], $int_conf_width);
		$int_thumb_width = $arr_thumbs[1];
		$int_thumb_height = $arr_thumbs[0];
	}
	else{
		$arr_thumbs = getImageRate($pam_params["file_width"],$pam_params["file_height"], $int_conf_height);
		$int_thumb_width = $arr_thumbs[0];
		$int_thumb_height = $arr_thumbs[1];
	}

	//文件不存在，错误
	if(@!file_exists($str_file_name)) return false;

	//错误的压缩次数
	if(!is_numeric($int_times)) return false;
	//循环并压缩
	$arr_thumb_all = array();
	//最终压缩的文件大小
	$arr_thumb_all[] = array("width" => $int_thumb_width, "height" => $int_thumb_height);

	//把每次压缩的比例放进数组中，由小到大排序
	for($i = 1 ; $i < $int_times ; $i ++){
		$tmp_img_width  = ($pam_params["file_width"] - $int_conf_width) * ($i/$int_times) + $int_conf_width;
		$tmp_img_height = ($pam_params["file_height"] - $int_conf_height) * ($i/$int_times) + $int_conf_height;
		$arr_thumb_all[] = array("width" => $tmp_img_width, "height" => $tmp_img_height);
	}
	//print_r($arr_thumb_all);
	$obj_images = new cls_image();
	//开始压缩
	//gif jpeg png
	if ($str_img_type == 'jpg' || empty($str_img_type))
	{
		$str_img_type = 'jpeg';
	}
	require_once ROOT_PATH . 'includes/inc_thumb.php';
	for($s = count($arr_thumb_all) ; $s > 0  ; $s --){
		//首次压缩，原图是用户上传的图片，然后是缩略图中抽取图片压缩
		if($s == count($arr_thumb_all)){
			createThumb($str_path . $str_thumb_name,$str_file_name,ceil($arr_thumb_all[$s - 1]["width"]),ceil($arr_thumb_all[$s - 1]["height"]),$str_img_type);

		}
		else{
			createThumb($str_path . $str_thumb_name,$str_path . $str_thumb_name,ceil($arr_thumb_all[$s - 1]["width"]),ceil($arr_thumb_all[$s - 1]["height"]),$str_img_type);
		}
		//sleep(3);
	}
//	echo microtime();
//	echo "总共花费：" . $n . "秒<br /><br />";
	//注销对象
	$obj_images = NULL;
	//执行到此，返回正确
	return true;
}

?>
